package com.qf.sl.youshare.tasks;

import android.os.AsyncTask;
import com.qf.sl.youshare.Constants;
import com.qf.sl.youshare.utils.HttpTools;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * Created by IDEA
 * User : sl
 * on 2015/2/5.
 * 10:19
 */
public class UserLoginTask extends AsyncTask<String, Integer, JSONObject>  {

    private TaskProcessor processor;

    public UserLoginTask(TaskProcessor processor) {
        this.processor = processor;
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        JSONObject ret = null;

        if (params != null && params.length >= 2) {
            String name = params[0];
            String password = params[1];

            String url = Constants.USER_URL + "?ac=login";

            System.out.println("url = " + url);

            HashMap<String, String> map = new HashMap<String, String>();

            map.put("user",name);

            System.out.println("name = " + name);

            map.put("password",password);

            System.out.println("pass = " + password);

            byte[] bytes = HttpTools.post(url, map);

            if (bytes != null) {
                try {
                    String string = new String(bytes,"utf-8");

                    System.out.println("string = " + string);

                    ret = new JSONObject(string);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


//            HttpPost request = new HttpPost("http://open.doushangshang.com/user/login.php");
//            //设置参数
//            HttpClient client = new DefaultHttpClient();
//
//            try {
//                HttpResponse response = client.execute(request);
//
//                StatusLine statusLine = response.getStatusLine();
//                if (statusLine.getStatusCode() == 200){
//                    HttpEntity entity = response.getEntity();
//                    byte[] bytes = EntityUtils.toByteArray(entity);
//                    ret = new String(bytes,"utf-8");
//                }
//
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }

        return ret;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        if (processor != null) {
            processor.processResult(jsonObject);
        }
    }
}
